package entity

import (
	"regexp"
	"save-kindle/source/ddd/definition"
	"save-kindle/source/ddd/dp"
	"strings"
)

// Page 正文
type Page struct {
	dp.BookPage

	PageParser definition.PageParser

	Content *Content
}

func NewPage(chapter dp.BookChapter, parser definition.Parser, pageNo int) *Page {
	pageHtml := parser.ParserPage(chapter, pageNo)
	c := NewContent(parser)
	c.getLines(pageHtml)

	return &Page{
		BookPage: dp.BookPage{
			BookSource:  chapter.BookSource,
			PageUrl:     parser.GetPageUrl(chapter, pageNo),
			PageHtml:    pageHtml,
			HasNextPage: parser.HasNextPage(pageHtml),
		},
		PageParser: parser,
		Content:    c,
	}
}

func (p *Page) GetCurrentPageStr() string {
	return p.Content.getLinesString()
}

// NewContent
func NewContent(parser definition.ContentParser) *Content {
	return &Content{
		ContentParser: parser,
	}
}

// Content 正文
type Content struct {
	ContentParser definition.ContentParser
	lines         []string
}

// GetLines 获取当前页的 文本内容
func (content *Content) getLines(pageHtml string) []string {
	if content.lines == nil {
		content.lines = content.ContentParser.ParserContent(pageHtml)
	}
	return content.lines
}

func (content *Content) getLinesString() string {
	sb := strings.Builder{}

	lineCount := len(content.lines)
	for i := 0; i < lineCount-1; i++ {
		sb.WriteString(content.lines[i] + "\n")
	}
	sb.WriteString(content.lines[lineCount-1])

	// 处理最后一行
	if regexp.MustCompile("[.。…”\"!！]$").MatchString(content.lines[lineCount-1]) {
		sb.WriteString("\n")
	}
	return sb.String()
}
